﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using yeqw.FrameWork;
namespace com.gyz.hao.WinCapInfoApp.Model
{
    public class AppConfigInfo
    {
        #region 属性
        /// <summary>
        /// 日志文件路径
        /// </summary>
        public string LogFilePath
        {
            get { return _logfilepath; }
        }
        private string _logfilepath;
        /// <summary>
        /// 抓取对象最大重复次数
        /// </summary>
        public int MaxReCount
        {
            get { return _maxrecount; }
        }
        private int _maxrecount = 3;
        //是否分组采集
        public bool GroupCollect = false;
        //线程休眠时间
        public int sleeptime { set; get; }
        /// <summary>
        /// 抓取器编号
        /// </summary>
        public int ComputeNo
        {
            get { return _computeno; }
        }
        private int _computeno = 3;
        
        /// <summary>
        /// 停止
        /// </summary>
        public bool IsStop { set; get; }

        /// <summary>
        /// 是否写入打开调试模式
        /// </summary>
        public bool IsDebug
        {
            get { return _isdebug; }
        }
        private bool _isdebug;

        /// <summary>
        /// 是否写入日志
        /// </summary>
        public bool IsWriteLog
        {
            get { return _iswritelog; }
        }
        private bool _iswritelog;

        //用于sql分页
        public int CollectNum { set; get; }

        public int CollectItem { set; get; }
        
        /// <summary>
        /// 已抓取数
        /// </summary>
        public int CapCount { set; get; }
        /// <summary>
        /// 抓取成功数
        /// </summary>

        public int SuccessCount { set; get; }
        /// <summary>
        /// 抓取失败数
        /// </summary>
        public int FailCount { set; get; }
        public int TotalOnlineCount { set; get; }
        public int TotalCloseCount { set; get; }
        /// <summary>
        /// 抓取总数
        /// </summary>
        public int CapTotalCount
        {
            get { return _captotalcount; }
        }
        private int _captotalcount;

        
        /// <summary>
        /// 抓取开始时间
        /// </summary>
        public DateTime StartTime { set; get; }
        /// <summary>
        /// 抓取结束时间
        /// </summary>
        public DateTime EndTime { set; get; }

        /// <summary>
        /// 组集合
        /// </summary>
        public List<GroupInfo> GroupList { set; get; }
        /// <summary>
        /// 规则集合
        /// </summary>
        public List<WebMatchConfigInfo> WebMatchList { set; get; }
        /// <summary>
        /// 抓取集合
        /// </summary>
        public List<CapInfo> CapInfoList { set; get; }

       
        #endregion


        public delegate void WriteLogInfoHandler(string logmsg);
        public event WriteLogInfoHandler WriteLogInfoEvent;

        public delegate void WriteCapInfoHandler(string msg);
        public event WriteCapInfoHandler WriteCapInfoEvent;

        public static AppConfigInfo AppConfig
        {
            get
            {
                if (instance == null)
                {
                    throw new Exception("系统数据未初始化");
                }
                return instance;
            }
        }


        private static AppConfigInfo instance;
        private static readonly object _object = new object();
        private AppConfigInfo()
        {
        }

        public static AppConfigInfo GetInstance(string xmlfilename)
        {
            //先判断实例是否存在，不存在再加锁处理
            if (instance == null)
            {
                //在同一时刻加了锁的那部分程序只有一个线程可以进入，
                lock (_object)
                {
                    //如实例不存在，则New一个新实例，否则返回已有实例
                    if (instance == null)
                    {
                        instance = new AppConfigInfo();
                        instance.GroupList = new List<GroupInfo>();
                        instance.WebMatchList = new List<WebMatchConfigInfo>();
                    }
                }
            }
            
            //这里解析XML 对变量赋值
            XmlDocument doc = new XmlDocument();
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;




            XmlReader reader = XmlReader.Create(xmlfilename, settings);
            doc.Load(reader);
            XmlNode rootNode = doc.SelectSingleNode("app");
            instance.sleeptime = rootNode["sleeptime"].InnerText.ToInt32(); ;
            instance._computeno = rootNode["computeno"].InnerText.ToInt32();
            instance._maxrecount = rootNode["maxrecount"].InnerText.ToInt32();
            instance._isdebug = Convert.ToBoolean(rootNode["isdebug"].InnerText);
            instance._iswritelog = Convert.ToBoolean(rootNode["iswritelog"].InnerText);
            instance._logfilepath = rootNode["logfilepath"].InnerText;

            //获取组信息
            GroupInfo model = new GroupInfo();
            doc = new XmlDocument();
            settings = new XmlReaderSettings();
            settings.IgnoreComments = true;//忽略xml注释
            xmlfilename = AppDomain.CurrentDomain.BaseDirectory + "\\XMLData\\GroupConfig.xml";
            reader = XmlReader.Create(xmlfilename, settings);
            doc.Load(reader);
            rootNode = doc.SelectSingleNode("groups");
            foreach (XmlNode node in rootNode.ChildNodes)
            {
                model = new GroupInfo();
                model.ID = node["id"].InnerText.ToInt32();
                model.CapTime = node["captime"].InnerText.ToInt32();
                instance.GroupList.Add(model);
            }

            //获取抓取规则信息
           
            doc = new XmlDocument();
            xmlfilename = AppDomain.CurrentDomain.BaseDirectory + "\\XMLData\\WebMatchConfig.xml";
            settings = new XmlReaderSettings();
            settings.IgnoreComments = true;//忽略xml注释

            reader = XmlReader.Create(xmlfilename, settings);
            doc.Load(reader);

            WebMatchConfigInfo matchmodel = new WebMatchConfigInfo();
            rootNode = doc.SelectSingleNode("//web");
            foreach (XmlNode node in rootNode.ChildNodes)
            {
                matchmodel = new WebMatchConfigInfo();
                matchmodel.SiteID = Convert.ToInt32(node.Attributes["id"].Value);
                if(node["url"]!=null)
                    matchmodel.Url = node["url"].InnerText;
                matchmodel.UrlMetod = node["urlmetod"].InnerText;
                matchmodel.MatchMetod = node["matchmetod"].InnerText;
                matchmodel.Match = node["match"].InnerText;
                matchmodel.Encoding = node["encoding"].InnerText;

                instance.WebMatchList.Add(matchmodel);
            }
            
            return instance;
        }
        /// <summary>
        /// 获取组信息
        /// </summary>
        /// <param name="groupID"></param>
        /// <returns></returns>
        public List<CapInfo> GetCapInfoListByGroupID(int groupID)
        {
            return instance.CapInfoList.FindAll(m => m.groupid == groupID);
        }
        /// <summary>
        /// 获取抓取规则信息
        /// </summary>
        /// <param name="siteid"></param>
        /// <returns></returns>
        public WebMatchConfigInfo GetMatchInfo(int siteid)
        {
            return instance.WebMatchList.Find(m => m.SiteID == siteid);
        }
        
        public void WriteCapMsg(string msg)//将消息显示在桌面上
        {
               string tmp = string.Format("{0}", msg);
               if (WriteCapInfoEvent != null)
               {
                   WriteCapInfoEvent.Invoke(tmp);
               }
        }
        public void WriteMsg(string msg)
        {
            WriteMsg(msg, true);
        }
        public void WriteMsg(string msg, bool isWriteLog)//将日志记录下来
        {
            string tmp = string.Format("[{0:yyyy-MM-dd HH:mm:ss.fff}]\t{1}\r\n", DateTime.Now, msg);
           // WriteLogInfoEvent?.Invoke(tmp);
            if (AppConfigInfo.AppConfig.IsWriteLog && isWriteLog)
            {
                //这里写日志。日志路径要是每个站点一个文件夹，每天一个文件夹/每一次抓取任务一个文件。
                string logfilename = AppConfigInfo.AppConfig.LogFilePath + "{0}\\{1}.txt".FormatExtension(DateTime.Now.Month.ToString("00"), DateTime.Now.ToAllDateString());
                FileHelper.WriteLogFile(logfilename, msg);

            }

        }
    }
}
